package Sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BucketSort {
    public static void bucketSort(int[] array){
        //确定桶的数量
        int maxNum = array[0];
        int minNum = array[0];
        for (int i = 0; i < array.length; i++) {
            if(maxNum<array[i]){
                maxNum = array[i];
            }
            if(minNum>array[i]){
                minNum = array[i];
            }
        }
        int bucketNum = (maxNum-minNum)/10+1;

        //初始化桶
        List<List<Integer>> lists = new ArrayList<>(bucketNum);

        for (int i = 0; i < bucketNum; i++) {
            lists.add(new ArrayList<>());
        }
        //元素分配到对应的桶

        for (int i = 0; i < array.length; i++) {
            int index = (array[i]-minNum)/10;
            lists.get(index).add(array[i]);
        }
        //对每个桶内的数据进行排序
        for (int i = 0; i < lists.size(); i++) {
            Collections.sort(lists.get(i));
        }
        //逐个取出桶内的数据
        int index1 = 0;
        for (int i = 0; i < lists.size(); i++) {
            for (int j = 0; j < lists.get(i).size(); j++) {
                array[index1++] = lists.get(i).get(j);
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {5, 3, 8, 4, 2};
        bucketSort(array);
        for (int num : array) {
            System.out.print(num + " ");
        }
    }
}
